package com.alex.tinyurl.service.store.db;

import com.alex.tinyurl.service.store.UrlMappingStore;
import com.alex.tinyurl.service.store.db.dao.UrlMappingEntityDao;
import com.alex.tinyurl.service.store.db.entity.UrlMappingEntity;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.Optional;

@Service
@ConditionalOnProperty(prefix = "tinyurl", name = "store.strategy", havingValue = "db")
@Setter
public class DBUrlMappingStore implements UrlMappingStore {

    @Autowired
    private UrlMappingEntityDao urlMappingEntityDao;

    @Override
    public boolean saveUrlMap(String tinyUrl, String originalUrl) {
        int addRet = urlMappingEntityDao.add(UrlMappingEntity.getInstance(tinyUrl, originalUrl));
        return addRet > 0;
    }

    @Override
    public Optional<String> getOriginalUrl(String tinyUrl) {
        UrlMappingEntity e = urlMappingEntityDao.getByTinyUrl(tinyUrl);
        if (Objects.isNull(e)) {
            return Optional.empty();
        }
        return Optional.of(e.getOriginalUrl());
    }

    @Override
    public Optional<String> getTinyUrl(String originalUrl) {
        UrlMappingEntity e = urlMappingEntityDao.getByOriginalUrl(originalUrl);
        if (Objects.isNull(e)) {
            return Optional.empty();
        }
        return Optional.of(e.getTinyUrl());
    }
}
